package org.thread.test04.sync.demo03;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ZQX
 * @date 2025-03-12
 */
public class MyRunnable implements Runnable {
    /**
     * 电影票 - 50张
     */
    private int ticket = 50;

    private ReentrantLock reentrantLock = new ReentrantLock();

    @Override
    public void run() {
        // 要注意锁的临界区范围 - 否则别的线程没有机会进来！！
        while (true) {
            try{
                // 加锁
                reentrantLock.lock();
                if (ticket <= 0) {
                    break;
                }

                String name = Thread.currentThread().getName();
                System.out.printf("%s 出售了第 %d 张电影票！%n", name, ticket);
                ticket--;
            } finally {
                // 解锁
                reentrantLock.unlock();
            }
        }

    }
}
